if minetest.setting_getbool("gauge_hp_entity")~= false then
	minetest.setting_set("gauge_hp_entity", "true")
end

local hp_bar = {
	physical = false,
	collisionbox = {x=0, y=0, z=0},
	visual = "sprite",
	textures = {"20.png"},
	visual_size = {x=1, y=1/16, z=1},
	wielder = nil,
}

function hp_bar:on_step(dtime)
	if minetest.setting_getbool("gauge_hp_entity")~= false then
		local wielder = self.wielder
		if wielder == nil then 
			self.object:remove()
			return   
		elseif wielder:get_player_name()~=nil and wielder:get_player_name()~="" and minetest.env:get_player_by_name(wielder:get_player_name()) == nil then 
			self.object:remove()
			return 
		end
		local hp = wielder:get_hp()
		self.object:set_properties({
			textures = {tostring(hp)..".png",},
		})   
	end
end

minetest.register_entity("lunogauges:hp_bar_entity", hp_bar)

function add_HP_gauge(player)
	if minetest.setting_getbool("gauge_hp_entity")~= false then
		if player~=nil and player:is_player() then --Caso de erro!!!
			local pos = player:getpos()
			local ent = minetest.env:add_entity(pos, "lunogauges:hp_bar_entity")
			if ent~= nil then
				ent:set_attach(player, "", {x=0,y=9,z=0}, {x=0,y=0,z=0})
				ent = ent:get_luaentity() 
				ent.wielder = player       
			end
		end
	end
end

--minetest.register_on_joinplayer(add_HP_gauge)

minetest.register_chatcommand("gaugehp", {
	params = "",
	description = "Ativa ou Desativa o barra de HP sobre a cabeca de todos os jogadores.",
	privs = {},
	func = function(name, param)
		if minetest.setting_getbool("gauge_hp_entity")==nil or minetest.setting_getbool("gauge_hp_entity")==true then
			minetest.setting_set("gauge_hp_entity", "false")
			minetest.chat_send_player(name, "Os jogadores que relogarem nao terao barra de HP.")
		else
			minetest.setting_set("gauge_hp_entity", "true")
			minetest.chat_send_player(name, "Os jogadores que relogarem terao barra de HP.")
		end
		return true
	end,
})

minetest.register_on_joinplayer(function(player)
	add_HP_gauge(player)
end)

